<template>
	<div class="form">
		<h1>账号登录</h1>
		<el-form ref="ruleFormRef" :model="ruleForm" :rules="rules" class="demo-ruleForm">
			<el-form-item prop="userNameOrEmail">
				<el-input v-model="ruleForm.userNameOrEmail" placeholder="用户名/邮箱" :prefix-icon="User" />
			</el-form-item>
			<el-form-item prop="password">
				<el-input show-password v-model="ruleForm.password" placeholder="密码" :prefix-icon="Lock" />
			</el-form-item>
			<div class="expansion">
				<router-link to="/register" class="register">立即注册</router-link>
				<router-link to="/changepassword" class="forget">忘记密码</router-link>
			</div>
			<el-form-item>
				<el-button type="primary" :loading="btnLoading" @click="submitForm(ruleFormRef)">登录</el-button>
			</el-form-item>
		</el-form>
	</div>
</template>

<script lang="ts" setup>
import { User, Lock } from "@element-plus/icons-vue";
import { reactive, ref } from "vue";
import { getUserinfo, Login } from "@/api/login";
import type { FormInstance, FormRules } from "element-plus";
import { useUserinfoStore } from "@/stores/userinfo";
const userinfo = useUserinfoStore();
const ruleFormRef = ref<FormInstance>();
const ruleForm = reactive({
	userNameOrEmail: "",
	password: ""
});

const rules = reactive<FormRules>({
	userNameOrEmail: [{ required: true, message: "用户名不能为空", trigger: "blur" }],
	password: [{ required: true, message: "密码不能为空", trigger: "blur" }]
});

const btnLoading = ref(false);
const submitForm = async (formEl: FormInstance | undefined) => {
	btnLoading.value = true;
	await formEl?.validate(async valid => {
		if (valid) {
			try {
				//如果登陆失败直接抛出错误，下面获得信息部分就没了
				const { data: data1 } = await Login(ruleForm);
				userinfo.setToken(data1.data);

				const { data: data2 } = await getUserinfo(data1.data);
				userinfo.setUserinfo(data2.data);
			} finally {
				btnLoading.value = false;
			}
		} else {
			btnLoading.value = false;
		}
	});
};
</script>
<style scoped lang="scss">
.form {
	width: 270px;
	height: 190px;
	display: flex;
	flex-direction: column;
	align-items: center;
	margin-right: 100px;
	background-color: #fff;
	h1 {
		font-size: 16px;
		margin-bottom: 5px;
	}
	.el-form {
		width: 235px;
	}
	.expansion {
		font-size: 10px;
		margin-bottom: 8px;
		display: flex;
		justify-content: space-between;
		a {
			color: #808080;
		}
	}
	.el-button {
		width: 100%;
	}
}
</style>
